package net.monare.mifss.admin.ui;

import java.util.Collection;

import net.monare.mifss.MifssAdminMainUI;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import com.vaadin.navigator.Navigator;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class AdminView extends VerticalLayout implements View {

	private static final long serialVersionUID = 1548337294828763472L;

	public void enter(ViewChangeEvent changeEvent) {

		removeAllComponents();

        SecurityContext securityContext = ((MifssAdminMainUI)UI.getCurrent()).getSecurityContext();


        Authentication authentication = securityContext.getAuthentication();

		if (authentication != null && authentication.isAuthenticated()) {

			Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

			for (GrantedAuthority ga : authorities) {

				String authority = ga.getAuthority();

				if ("ROLE_ADMIN".equals(authority)) {

					// load component
					addComponent(new AdminWorkPanel());

				}

			}

		} else {
			Navigator navigator = UI.getCurrent().getNavigator();
			navigator.navigateTo("login");
		}
	}

}
